<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="模板基本信息">
        <a-row :gutter="48">
          <a-col :span="8">
            <a-form-model-item label="模板编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="templateNo">
              <a-input  v-model="model.templateNo" placeholder="请输入模板编号"  disabled ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="模板名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="templateName">
              <a-input :disabled=formDisabled v-model="model.templateName" placeholder="请输入模板名称"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="模板类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="templateType">
              <j-dict-select-tag :disabled=formDisabled type="list" v-model="model.templateType" dictCode="template_type" placeholder="请选择模板类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="业务分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bussinessType">
              <j-dict-select-tag :disabled=formDisabled type="list" v-model="model.bussinessType" dictCode="ywfx_type" placeholder="请选择业务分类" />
            </a-form-model-item>
          </a-col>
          <a-col :span="16">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-textarea :disabled="formDisabled" v-model="model.remark" rows="4" placeholder="请输入备注"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="经办人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handlerId">
              <select-person-input
                :disabled=formDisabled
                v-model="model.handlerId" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="经办部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handlerDeptId">
              <j-select-depart :disabled=formDisabled v-model="model.handlerDeptId" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="创建时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
              <j-date :disabled=formDisabled placeholder="请选择创建时间" v-model="model.createTime"  date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
        </a-row>
          </a-collapse-panel>
          <!--          业务分类-->
          <a-collapse-panel key="2" header="进度节点信息">
            <a-row>
            <a-col :span="24">
              <div style="margin-bottom: 6px;margin-top: 6px">
                <a-button @click="handleAdd" v-if="!formDisabled" type="primary">新增</a-button>
              </div>
              <a-table
                ref="table"
                size="middle"
                rowKey="id"
                :loading="loading"
                :columns="columns"
                :pagination="false"
                :data-source="dataSource">
                  <span slot="action" slot-scope="text, record">
                    <template v-if="!formDisabled">
                            <a-button
                              class="ruleButton"
                              :ghost="true"
                              type="primary"
                              icon="edit"
                              @click="handleEdit(record)"/>
                            <a-divider type="vertical"/>
                            <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                                <a-button
                                  class="ruleButton"
                                  :ghost="true"
                                  type="primary"
                                  icon="delete"
                                />
                            </a-popconfirm>
                    </template>
                 </span>
                <template slot="titleSlot" slot-scope="text">
                  <span  v-if="text">
                     {{text}}%
                  </span>
                  <span  v-if="!text">
                     -
                  </span>
                </template>
              </a-table>
            </a-col>
            <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
              <a-button @click="submitForm">提 交</a-button>
            </a-col>
          </a-row>
          </a-collapse-panel>
        </a-collapse>
        <erp-progress-template-dt-modal ref="itemList" @ok="modalFormOk"></erp-progress-template-dt-modal>

      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { filterObj, validateDuplicateValue } from '@/utils/util'
  import SelectPersonInput from '@/views/scy/components/SelectPersonInput'
  import ErpProgressTemplateDtModal from './ErpProgressTemplateDtModal.vue'
  import { mapGetters } from 'vuex';
  import moment from 'moment';
  export default {
    name: 'ErpProgressTemplateDetailForm',
    components: {
      SelectPersonInput,
      ErpProgressTemplateDtModal
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        /* 排序参数 */
        isorter: {
          column: 'sortOrder',
          order: 'desc'
        },
        activeKey: ['1','2'],
        model:{
         },
        loading: false,
        labelCol: {
        },
        columns: [
          {
            title: '节点名称',
            align: 'center',
            dataIndex: 'nodeName',
          },
          {
            title: '节点进度',
            align: 'center',
            dataIndex: 'nodeProgress',
            scopedSlots: { customRender: 'titleSlot' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            scopedSlots: {
              filterDropdown: 'filterDropdown',
              filterIcon: 'filterIcon',
              customRender: 'action'
            }
          }
        ],
        dataSource: [],
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        validatorRules: {
          templateName: [
            { required: true, message: '请输入模板名称!',whitespace:true},
          ],
        },
        url: {
          addOrEdit: "/api/erp/progress/erpProgressTemplate/addOrEdit",
          edit: "/api/erp/progress/erpProgressTemplate/addOrEdit",
          queryById: "/api/erp/progress/erpProgressTemplate/queryById",
          erpProgressTemplateDtList: '/api/erp/progress/erpProgressTemplateDt/list',
          generatedFormNumber: '/api/erp/base/generatedFormNumber'
        }
      }
    },
    computed: {

      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      generatedFormNumber() {
        getAction(this.url.generatedFormNumber, { prefix: 'ERPJDMB', subSystemCode: '05' }).then(res => {
          if (res.success) {
            //this.model.templateNo = res.result
            this.$set(this.model,"templateNo",res.result);
          }
        })
      },
      handleAdd () {
        this.$refs.itemList.add();
        this.$refs.itemList.title = '模板创建';
        this.$refs.itemList.disableSubmit = false;
      },
      handleEdit(record) {
        this.$refs.itemList.edit(record);
        this.$refs.itemList.title = '模板编辑';
        this.$refs.itemList.disableSubmit = false;
      },
      handleDelete(id) {
        for (let i = 0; i < this.dataSource.length; i++) {
          if (this.dataSource[i].id == id) {
            this.dataSource.splice(i, 1);
          }
        }
      },
      modalFormOk(data) {
        this.loading = true;
        let flag = true;
        // debugger;
        for (let i = 0; i < this.dataSource.length; i++) {
          if (this.dataSource[i].id == data.id) {
            this.dataSource.splice(i, 1, data);
            flag = false;
          }
        }
        if (flag) {
          this.dataSource.push(data);
        }
        this.loading = false;
      },
      ...mapGetters(['userInfo']),
      add (value) {
        this.dataSource = []
        this.edit(this.modelDefault);
        this.model.handlerId = this.userInfo().empId;
        // this.model.handlerName=value.loginUser.realname;
        this.model.handlerDeptId = this.userInfo().deptId;
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
      },
      edit (record) {
        this.$refs.form.resetFields();
        this.model = Object.assign({}, record);
        if (this.model.id) {
          getAction(this.url.erpProgressTemplateDtList, { mainId: this.model.id }).then((res) => {
            if (res.success) {
              this.dataSource = res.result.records || res.result
            }
          })
        } else {
          this.generatedFormNumber();
        }
        this.visible = true;
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          });
        }
      },
      getQueryParams() {
        let param = Object.assign({}, {}, this.isorter);
        return filterObj(param);
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = this.url.addOrEdit;
            let method = 'post';
            this.model.erpProgressTemplateDtList = this.dataSource;
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
    }
  }
</script>
